import { _decorator, Component, Node, SpringJoint2D, Sprite, UITransform,Animation, AnimationClip, animation, SpriteFrame, random } from 'cc';
import { IEntity } from '../levels';
import { PlayerStateMachine } from '../Scripts/Player/PlayerStateMachine';
import { DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_TYPE_ENUM, ENTITY_STATE_ENUM, PARAMS_NAME_ENUM } from '../Enums';
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManager';
import { randomByLen } from '../Utils';
const { ccclass, property } = _decorator;


@ccclass('EntityManager')
export class EntityManager extends Component {
    id:string = randomByLen(12)
    x: number = 0                           // 当前X坐标
    y: number = 0                           // 当前Y坐标
    fsm: PlayerStateMachine                 // 状态机实例
    private _direction: DIRECTION_ENUM      // 方向
    private _state:ENTITY_STATE_ENUM        // 状态
    type:ENTITY_TYPE_ENUM           // 实体类型

    get direction(){
      return this._direction
    }

    set direction(newDirection:DIRECTION_ENUM){
      this._direction=newDirection
      this.fsm.setParams(PARAMS_NAME_ENUM.DIRECTION, DIRECTION_ORDER_ENUM[this._direction])
    }
    get state(){
      return this._state
    }

    set state(newState:ENTITY_STATE_ENUM){
      this._state=newState
      this.fsm.setParams(newState, true)
    }

    // 初始化
    async init(params:IEntity) {
      // 1. 设置精灵组件
      const sprite = this.addComponent(Sprite)
      sprite.sizeMode = Sprite.SizeMode.CUSTOM

      // 2. 设置尺寸
      const transform = this.getComponent(UITransform)
      transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4)

      // 3. 初始化状态机
      this.x=params.x
      this.y=params.y
      this.type=params.type
      this.direction=params.direction
      this.state=params.state
    }

    update() {
      // 设置节点位置（包含偏移计算）
      this.node.setPosition(
        this.x * TILE_WIDTH - 1.5 * TILE_WIDTH,
        -this.y * TILE_HEIGHT + 1.5 * TILE_HEIGHT
      )
    }

    onDestroy(){

    }
}


